<?php
namespace App\Models\Common;

use App\Models\Tools\AliOss;
use EasyWeChat\Kernel\Http\StreamResponse;
use Illuminate\Support\Facades\Log;

class File
{

    /**
     * 保存微信上传的媒体文件（主要是图片）
     * @param string $media_id
     * @param string $file_path
     * @return bool|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     */
    public static function saveMedia($media_id, $file_path)
    {

        $app = app('wechat.official_account');
        $stream = $app->media->get($media_id);
        if ($stream instanceof StreamResponse) {
            // 保存到本地
            $filename = $file_path . '/' . $stream->save('storage/' . $file_path);
            // 保存到云端OSS
            $result = AliOss::uploadFileSimplify($filename);
            if (!$result) {
                Log::error(File::class, ['msg' => 'oss保存图片失败', 'result' => $result]);
                return false;
            }
            return $filename;
        } else {
            if (env('APP_ENV') === 'local') {
                return false;
            }
            Log::error(File::class, ['stream' => $stream]);
            return false;
        }

    }

}
